<template>
  <div>
    <div class="margin-left relative">
      <div class="headDiv">
        <span style="font-size:14px" class="text-bold margin-right-sm"
          >申请开票</span
        >
      </div>
    </div>

    <el-row>
      <el-col :span="tableWidth">
        <el-card>
          <el-form :model="criteriaForm" ref="basisForm" size="mini">
            <el-row>
              <el-col :span="4">
                <el-form-item
                  label="运单号"
                  label-width="70px"
                  prop="waybillNoTextArea"
                >
                  <el-input
                    size="large"
                    v-model="criteriaForm.waybillNoTextArea"
                    type="textarea"
                    name="waybillName"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  label="应收客户"
                  label-width="70px"
                  prop="customerId"
                >
                  <template>
                    <el-select
                      v-if="!cus"
                      style="width: 70%"
                      v-model="criteriaForm.customerId"
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="getCustomerMap"
                      placeholder="请输入客户名称"
                    >
                      <el-option
                        v-for="(item, value) in customerRemoteSource"
                        :key="value"
                        :label="item"
                        :value="parseInt(value)"
                      >
                      </el-option>
                    </el-select>
                    <el-select
                      v-else
                      style="width: 70%"
                      v-model="criteriaForm.customerId"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入客户名称"
                    >
                      <el-option
                        v-for="(item, value) in customerSource"
                        :key="value"
                        :label="item"
                        :value="parseInt(value)"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item
                  label="费用名称"
                  label-width="70px"
                  prop="costName"
                >
                  <el-select
                    size="mini"
                    multiple
                    filterable
                    clearable
                    v-model="criteriaForm.costName"
                  >
                    <el-option
                      v-for="(item, value) in costNameSource"
                      :key="value"
                      :label="item"
                      :value="parseInt(value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="币种：" label-width="70px" prop="currency">
                  <el-select
                    v-model="criteriaForm.currency"
                    multiple
                    size="mini"
                  >
                    <el-option
                      v-for="(item, value) in currencySource"
                      :key="value"
                      :label="item"
                      :value="value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="3">
                <el-form-item label="销售：" label-width="70px" prop="saleId">
                  <el-select
                    v-model="criteriaForm.saleId"
                    placeholder="请选择销售"
                    clearable
                    filterable
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="(k, v) in userOptions"
                      :key="v"
                      :label="userOptions[v]"
                      :value="parseInt(v)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="3">
                <el-form-item
                  label="开票状态："
                  label-width="80px"
                  prop="invoicestate"
                >
                  <el-select v-model="criteriaForm.invoicestate" size="mini">
                    <el-option
                      v-for="(item, value) in invoiceStatusSource"
                      :key="value"
                      :label="item"
                      :value="value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="3">
                <el-button
                  size="mini"
                  type="primary"
                  style="margin-left: 10px"
                  @click="query"
                  >查询</el-button
                >
                <el-button size="mini" @click="reset">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <el-dialog title="账单信息" :visible.sync="applyDialog">
          <el-form
            :model="applyForm"
            :rules="rules"
            ref="applyForm"
            label-width="30%"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="已开金额" prop="hasopenAccount">
                  <el-input
                    size="mini"
                    disabled
                    v-model="applyForm.hasopenAccount"
                    style="width:70%"
                  />
                </el-form-item>
                <el-form-item label="申请金额" prop="applyaccount">
                  <el-input
                    disabled
                    size="mini"
                    v-model="applyForm.applyaccount"
                    style="width:70%"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="电子/纸质" prop="invoicetype">
                  <el-select
                    size="mini"
                    v-model="applyForm.invoicetype"
                    style="width:70%"
                    clearable
                  >
                    <el-option
                      v-for="(v, i) in crmPapSource"
                      :key="i"
                      :value="i"
                      :label="v"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="未开金额" prop="notopenAccount">
                  <el-input
                    disabled
                    size="mini"
                    v-model="applyForm.notopenAccount"
                    style="width:70%"
                  />
                </el-form-item>
                <el-form-item label="抬头名称" prop="customerInvoice">
                  <el-select
                    size="mini"
                    v-model="applyForm.customerInvoice"
                    style="width:70%"
                    clearable
                  >
                    <el-option
                      v-for="(v, i) in customerInvoiceSource"
                      :key="i"
                      :label="v"
                      :value="parseInt(i)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="申请备注" prop="invoiceremark">
                  <el-input
                    type="textarea"
                    v-model="applyForm.invoiceremark"
                    style="width:70%"
                    placeholder="请填入客户地址等备注信息"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer">
            <el-button size="mini" @click="applyDialog = false">取消</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="applyinvoiceToFee('applyForm')"
              >确定</el-button
            >
          </div>
        </el-dialog>
        <el-card shadow="never">
          <el-button
            style="margin-right: -5px;float: right;background:#63D2A3;color:#ebf2ff"
            size="mini"
            @click="applyinvoice()"
            >申请开票</el-button
          >
          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="30"> </el-table-column>
            <el-table-column prop="waybillNo" label="运单号" width="180">
            </el-table-column>
            <el-table-column prop="saleManId" label="销售" width="180">
              <template slot-scope="scope">
                {{ userOptions[scope.row.saleManId] }}
              </template>
            </el-table-column>
            <el-table-column prop="serCusId" label="客户名称">
              <template slot-scope="scope">
                {{ customerSource[scope.row.serCusId] }}
              </template>
            </el-table-column>
            <el-table-column prop="costName" label="费用名称">
              <template slot-scope="scope">
                {{ costNameSource[scope.row.costName] }}
              </template>
            </el-table-column>
            <el-table-column
              prop="hasopenAccount"
              label="已开票金额"
              width="180"
            >
            </el-table-column>

            <el-table-column
              prop="invoicemoney"
              label="申请开票金额"
              width="180"
            >
            </el-table-column>
            <el-table-column prop="totalCost" label="总金额" width="180">
            </el-table-column>
            <el-table-column prop="currency" label="币种" width="180">
            </el-table-column>

            <el-table-column prop="invoicestate" label="开票状态">
              <template slot-scope="scope">
                {{
                  scope.row.invoicestate
                    ? invoiceStatusSource[scope.row.invoicestate]
                    : "未开票"
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="remark"
              label="备注"
              width="180"
            ></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 新增编辑费用弹窗 -->
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";

export default {
  props: ["field"],
  data() {
    return {
      applyDialog: false,
      currentPage: 1,
      pageSize: 500,
      totalSize: 0,
      indexFlag: true,
      list: {},
      userOptions: {},
      tableWidth: 24,
      multipleSelection: [],
      headtotalCost: "", //头部应收总计
      headtotalRemain: "", //头部余额
      headAppend: "", //头部合计
      criteriaForm: {},
      cus: false,
      customerSource: {}, // 客户
      customerRemoteSource: {}, //搜索的
      countrySource: {}, // 国家
      currencySource: {}, // 币种
      shippingWaySource: {}, // 物流方法
      shippingAddressSource: {}, // 起运地
      invoiceStatusSource: {
        0: "未开票",
        1: "开票中",
        2: "已开票"
      },
      costNameSource: {}, // 费用名称
      billTypeSource: {}, // 账单类型
      crmPapSource: {},
      customerInvoiceSource: {},
      tableData: [], //
      applyForm: {
        hasopenAccount: "",
        notopenAccount: "",
        applyaccount: "",
        invoicetype: "",
        customerInvoice: "",
        invoiceremark: ""
      },
      rules: {
        hasopenAccount: [
          { required: true, message: "请输入已开金额", trigger: "blur" }
        ],
        applyaccount: [
          { required: true, message: "请输入申请金额", trigger: "blur" }
        ],
        invoicetype: [
          { required: true, message: "请选择开票类型", trigger: "change" }
        ],
        notopenAccount: [
          { required: true, message: "请输入未开金额", trigger: "blur" }
        ],
        customerInvoice: [
          { required: true, message: "请选择抬头名称", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    this.init();
    this.initUserOptions("userSource");
  },
  methods: {
    applyinvoiceToFee() {
      var param = {};
      if (!this.applyForm.invoicetype) {
        this.$message.error("请选择发票类型：电子/纸质");
        return;
      }
      if (!this.applyForm.customerInvoice) {
        this.$message.error("请选择抬头");
        return;
      }
      param = this.applyForm;
      ajax("applyinvoiceToFee", param).then(
        res => {
          if (res.success) {
            window.open(
              `#/blank/customer__billinvoice__main?ids=${this.applyForm.ids}&customerId=${res.customerId}
              &invoicetype=${this.applyForm.invoicetype}&invoiceremark=${this.applyForm.invoiceremark}&customerInvoice=${this.applyForm.customerInvoice}`
            );
            console.log(res.success);
          } else {
            this.$message.error("系统错误");
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    async applyinvoice() {
      var params = {};
      params.id = this.criteriaForm.customerId;
      let res = await ajax("applyNoForInvoice", params);
      console.log(res);
      if (res.success) {
        console.log(this.multipleSelection);
        var overs = [];
        var totalMoney = 0.0;
        var totalHasMony = 0.0;
        var totalNot = 0.0;
        var ids = [];
        if (this.multipleSelection.length > 1) {
          this.multipleSelection.forEach(element => {
            ids.push(element.id);
            if (
              element.invoicestate &&
              (element.invoicestate == 2 || element.invoicestate == 1)
            ) {
              overs.push(element.id);
            }
            if (element.totalCost) {
              totalMoney += element.totalCost;
            }
            if (element.hasopenAccount) {
              totalHasMony += element.hasopenAccount;
            }
          });
        } else if (this.multipleSelection.length == 1) {
          this.multipleSelection.forEach(element => {
            ids.push(element.id);
            if (element.totalCost) {
              totalMoney += element.totalCost;
            }
            if (element.hasopenAccount) {
              totalHasMony += element.hasopenAccount;
            }
          });
        } else {
          this.$message.error("请选择费用开票");
          return;
        }
        totalNot = totalMoney - totalHasMony;
        this.applyForm.hasopenAccount = totalHasMony;
        this.applyForm.notopenAccount = totalNot;
        this.applyForm.applyaccount = totalNot;
        if (overs.length > 0) {
          this.$message.error(
            "存在已开票完成的费用 不能再次开票 或存在开票中的费用 请单独完成开票 请重新选择！"
          );
          return;
        }
        this.applyDialog = true;
        this.crmPapSource = res.crmPapSource;
        this.customerInvoiceSource = res.customerInvoiceSource;
        this.applyForm.customerInvoice = res.defaultCustomerInvoice;
        this.applyForm.ids = ids;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 资源文件
    m(val) {
      return m(val);
    },
    rowKey(row) {
      return row.id;
    },
    findKey(obj, value, compare = (a, b) => a === b) {
      return Object.keys(obj).find(k => compare(obj[k], value));
    },
    initUserOptions(bean) {
      var uri = "/api/entry/source?bean=" + bean;
      axios.post(constant.API_SERVER + uri).then(
        response => {
          this.userOptions = response.data;
        },
        error => {
          console.info(error);
        }
      );
    },

    async query() {
      // 获取表单数据
      let waybillQueryCriteria = this.criteriaForm;
      // 运单号
      let waybillNoTextArea = waybillQueryCriteria.waybillNoTextArea;
      if (waybillNoTextArea) {
        waybillQueryCriteria.waybillNos = waybillNoTextArea.split("\n");
      } else {
        waybillQueryCriteria.waybillNos = [];
      }

      // 客户
      if (!waybillQueryCriteria.customerId) {
        this.$message.error("请先选择客户");
        return;
      }

      // //分页参数
      waybillQueryCriteria.currentPage = this.currentPage;
      waybillQueryCriteria.pageSize = this.pageSize;

      this.loading = true;
      waybillQueryCriteria.currentPage = 1;
      let res = await ajax("query", waybillQueryCriteria);
      console.log(res);
      if (res.success) {
        console.log(res);
        this.customerSource = res.customerSource;
        this.tableData = res.waybillReceiveDetails;
      } else {
        return this.$message.error(m(res.message));
      }
      this.loading = false;
    },

    //根据条件搜索客户下拉
    async getCustomerMap(query) {
      let len = query.split(" ").join("").length;
      if (query !== "" && len > 0) {
        let map = await ajax("initCustomer", { customerNameShort: query });
        //console.log("map",map);
        this.customerRemoteSource = map;
      }
    },

    // 页面初始化
    async init() {
      this.updateId = this.$route.query.id;
      let customerId = this.criteriaForm.customerId;
      this.isShow = true;
      let data = {};
      if (customerId) {
        var regex = /^[0-9]*$/;
        var regExp = new RegExp(regex);
        if (!regExp.test(customerId)) {
          this.$message.error("客户ID非法");
          return;
        }
        data["customerId"] = customerId;
      }
      let res = await ajax("init", data);
      // 显示当前销售的所有客户
      this.customerSource = res.customerSource;

      this.countrySource = res.countrySource;
      this.currencySource = res.currencySource;
      this.shippingWaySource = res.shippingWaySource;
      this.shippingAddressSource = res.shippingAddressSource;
      this.costNameSource = res.costNameSource;
      this.billTypeSource = res.billTypeSource; //账单类型
    },

    // 重置
    reset() {
      location.reload();
    }
  }
};
</script>

<style scoped>
.maxheight {
  display: none;
}

.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  background-color: #409eff;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}
/deep/ .el-card {
  margin-top: 0px;
  margin-bottom: 10px;
  margin-left: 0px;
  margin-right: 0px;
}
.margin_bottom {
  margin-bottom: -20px;
}
.headDiv {
  position: fixed;
  top: 20px;
  z-index: 1001;
}
/deep/ .el-table th.gutter {
  display: table-cell !important;
}

/deep/ .el-table .cell {
  padding: 0;
}

/deep/ .el-table th.gutter {
  display: table-cell !important;
}
</style>
